<script setup>
  import {
    AddDataAPI,
    GetListAPI,
    EditDataAPI,
    GetViewAPI,
    DelDataAPI,
    GetdeptUserTreeAPI,
    DeliveryAPI,
    GetRoleAPI,
  } from "@/api/specialinspection/Issued";
  import {
    inspectionSceneDdlAPI,
    auditTypeDdlDdlAPI,
    gradeDdlAPI,
  } from "@/api/specialinspection/category";
  import SubmitForm from "./submitForm.vue";
  const { proxy } = getCurrentInstance();
  const router = useRouter();
  /**
   * 字典查询
   */
  const { Issued_status } = proxy.useDict("Issued_status");
  /**稽查场景 */
  const inspectionSceneList = ref([]);
  const gradeList = ref([]);
  /**
   * 模糊查询枚举
   */
  const selectList = ref([
    { type: "时间选择" },
    {
      label: "任务状态",
      model: "status",
      type: "下拉单选",
      opt: Issued_status,
    },

    {
      label: "稽查场景",
      model: "inspectionScene",
      type: "稽查场景",
      opt: inspectionSceneList,
    },

    {
      label: "稽查类别",
      model: "auditType",
      type: "下拉单选",
      opt: [],
    },
    {
      label: "等级",
      model: "grade",
      type: "下拉单选",
      opt: gradeList,
    },
  ]);
  /**
   * 表单实例
   */
  const ruleFormRef = ref(null);
  /**
   * 表单
   */
  const ruleForm = ref({});
  /**
   * 表格枚举
   */
  const columns = ref([
    { label: "任务单号", prop: "taskNo", width: "120" },
    { label: "任务状态", prop: "status", width: "120" },
    { label: "稽查场景", prop: "inspectionScene", width: "120" },
    { label: "稽查类别", prop: "auditType", width: "auto" },

    { label: "等级", prop: "grade", width: "auto" },
    { label: "创建时间", prop: "createTime", width: "150" },
    { label: "备注", prop: "remark", width: "120" },

    { label: "操作", prop: "x" },
  ]);

  /**
   * 树结构
   */
  const dataTree = ref([]);
  /**
   * 树结构枚举
   */
  const defaultProps = {
    children: "children",
    label: "categoryName",
    value: "id",
  };
  /**
   * 按钮枚举
   */
  const buttonList = ref([
    { type: "add", hasPermi: "mold:edger:add" },
    { type: "import", hasPermi: "mold:edger:import" },
    // { type: "export", hasPermi: "mold:edger:export" },
  ]);

  /**
   * 表格数据
   */
  const tableData = ref([]);

  /**
   * 表单实例
   */
  const submitFormRef = ref(null);

  /**
   * 一级类别列表
   */
  const categoryList = ref([]);
  /**
   * 新增修改表单
   */
  const submitForm = ref({});

  /**
   * 查询表单
   */
  const query = reactive({
    pageNum: 1,
    pageSize: 10,
  });

  const data = ref([]);
  const transfer = ref(null);
  /**
   * 表单校验
   */
  const rules = reactive({
    userIds: [{ required: true, message: "请选择人员", trigger: "change" }],
  });
  /**
   * 各种状态
   */
  const state = reactive({
    loading: false,
    total: 0,
    btnLoading: false,
    isShow: false,
    title: "新增",
    row: [],
    ids: [],
    treeShow: false, //树结构弹窗
  });

  /**
   * 新增弹窗
   */
  const addDic = () => {
    state.title = "新增";
    state.isShow = true;
  };

  /**等级 */

  const gradeDdl = async () => {
    const { data: res } = await gradeDdlAPI();

    gradeList.value = res.map((t) => {
      return {
        label: t.name,
        value: t.code,
      };
    });
  };
  gradeDdl();

  /*获取稽查场景 */
  const getInspectionScene = async () => {
    try {
      const { data: res } = await inspectionSceneDdlAPI();
      inspectionSceneList.value = res.map((t) => {
        return {
          label: t.name,
          value: t.code,
        };
      });
    } catch (err) {
      console.log(err);
    }
  };
  getInspectionScene();
  /**
   * 修改弹窗
   */
  const editDic = async (id) => {
    try {
      state.title = "下发";
      state.id = id;

      state.treeShow = true;
      getdeptUserTree();
    } catch (err) {
    } finally {
    }
  };

  /**
   * 查看弹窗
   */
  const lookDic = async (v) => {
    router.push(`/specialinspection/Issued/view?id=${v.id}&&status=${v.status}`);
  };

  /**
   * 弹窗关闭
   */
  const closeDic = () => {
    state.isShow = false;
    state.treeShow = false;
    submitForm.value = {};
    ruleForm.value = {};
  };
  /**稽查场景 */
  const inspectChange = async (v) => {
    const { data: res } = await auditTypeDdlDdlAPI({
      inspectionScene: v,
    });

    selectList.value[3].opt = res.map((t) => {
      return {
        label: t.name,
        value: t.code,
      };
    });
  };

  /**
   * 新增
   */
  const addSub = async () => {
    try {
      state.btnLoading = true;
      const result = await submitFormRef.value.submit();
      await AddDataAPI(result);
      closeDic();
      proxy.successMsg("新增成功");
      getList();
    } catch (err) {
      console.error(err);
    } finally {
      state.btnLoading = false;
    }
  };

  /**
   * 修改
   */
  const editSub = async () => {
    try {
      state.btnLoading = true;
      const result = await submitFormRef.value.submit();
      await EditDataAPI(result);
      closeDic();
      proxy.successMsg("修改成功");
      getList();
    } catch (err) {
      console.error(err);
    } finally {
      state.btnLoading = false;
    }
  };

  /**
   * 删除
   */
  const remove = async (id) => {
    try {
      proxy.loading("删除中，请稍后");
      await DelDataAPI(id);
      closeDic();
      proxy.successMsg("删除成功");
      getList();
    } catch (err) {
      console.error(err);
    } finally {
      proxy.closeLoading();
    }
  };

  /**
   * 模糊查询
   */
  const selectSubmit = (val) => {
    Object.keys(val).forEach((keyItem) => (query[keyItem] = val[keyItem]));
    query.startTime = query.beginTime;
    getList();
  };

  /**
   * 列表复选框
   */
  const handleSelectionChange = ({ row, ids }) => {
    state.ids = ids;
    state.row = row;
  };

  /**
   * 删除列表
   */
  const delTree = async (v) => {
    try {
      const isif = await proxy.MessageBox("是否删除？");
      if (!isif) return;
      proxy.loading("删除中，请稍后");
      await DelCategoryAPI(v.id);
      closeDic();
      proxy.successMsg("删除成功");
      getTreeList();
    } catch (err) {
      console.error(err);
    } finally {
      proxy.closeLoading();
    }
  };

  /**
   * 查询列表
   */
  const getList = async () => {
    try {
      state.loading = true;
      const { data: result } = await GetListAPI(query);
      state.total = result.total;
      tableData.value = result.result;
    } catch (err) {
      console.error(err);
    } finally {
      state.loading = false;
    }
  };
  const dataAll = ref([]);
  const roleList = ref([]);
  /**部门 */
  const getdeptUserTree = async () => {
    try {
      const { data: res } = await GetdeptUserTreeAPI();
      data.value = res;
    } catch (err) {
      console.error(err);
    } finally {
    }
  };
  /**角色 */
  const getRole = async () => {
    try {
      const { data: res } = await GetRoleAPI();
      roleList.value = res;
      console.log(roleList.value, "roleList.value");
    } catch (err) {
      console.error(err);
    } finally {
    }
  };
  getRole();
  /**
   * 下发人员
   */

  const addTreeSub = async () => {
    const valid = await transfer.value.submit();

    if (!valid) return;
    let obj = valid;
    console.log(valid, "valid");
    obj.id = state.id;
    await DeliveryAPI(obj);
    proxy.successMsg("下发成功");
    closeDic();
    getList();
  };
  /**
   * 重置
   */
  const close = () => {
    submitForm.value = {};
  };
  getList();
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="selectList" @selectSubmit="selectSubmit" @inspectChange="inspectChange" />

    <el-card>
      <p-button :list="buttonList" @add="addDic" @import="getList" :url="'/web/specialCheckTasks/upload'"
        :templateUrl="'/web/specialCheckTasks/export'" :importUrl="'/web/specialCheckTasks/upload'" />
      <!-- 表格数据 -->
      <p-table class="tableClass" :loading="state.loading" :data="tableData" :column="columns"
        v-model:page="query.pageNum" v-model:limit="query.pageSize" :total="state.total" @change="handleSelectionChange"
        @pagination="getList">
        <template #columnCell="{ column, record }">
          <p-dictTag v-if="column.prop == 'status'" :options="Issued_status" :value="record.status" />

          <p-operate :list="[
              {
                icon: 'Edit',
                emit: 'edit',
                disabled: record.status != 1,
                text: '下发',
                type: 'primary',
                hasPermi: 'mold:edger:edit',
              },
              {
                icon: 'DeleteFilled',
                emit: 'remove',
                disabled: record.status != 1,
                text: '删除',
                isDel: true,
                type: 'danger',
                hasPermi: 'mold:edger:remove',
              },
              {
                icon: 'Search',
                emit: 'look',
                disabled: false,
                text: '查看明细',
                type: 'primary',
                hasPermi: 'mold:edger:query',
              },
            ]" v-if="column.prop == 'x'" @look="lookDic(record)" @edit="editDic(record.id)"
            @remove="remove(record.id)" />
        </template>
      </p-table>
    </el-card>

    <!-- 弹窗 新增-修改 -->
    <p-dialog v-model="state.isShow" :title="state.title" @ok="state.title == '新增' ? addSub() : editSub()"
      @close="close" width="60%">
      <SubmitForm ref="submitFormRef" :data="submitForm" :disabled="state.title == '查看'" />
    </p-dialog>
    <!-- 树结构类别 -->
    <p-dialog v-model="state.treeShow" :title="state.title" @ok="addTreeSub()" @close="closeDic" width="40%">
      <p-transfer-tree ref="transfer" :dataAll="data" :checkedIds="checkedIds" :roleList="roleList" :titles="titles"
        @changeChecked="changeChecked" />
    </p-dialog>
  </div>
</template>

<style scoped lang="scss">
  .card-tree {
    height: 52.5rem;
    overflow: auto;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
  }
</style>